#include "Socket.h"
#include <iostream>

using namespace std;

Socket::Socket(){}

Socket::Socket(int port) : _port(port){}

Socket::~Socket(){}


void Socket::writeLine(const char *s)
{
  int fd = _sock;
  send(fd, s, strlen(s), 0);
  send(fd, "\n", 1, 0);
}

string Socket::readLine(int max)
{
  int fd = _sock;
  int i = 0, nb = 0;
  char chaine[max];
  do
    {
      nb = recv(fd, chaine+i, 1, 0);
      if(nb == -1)
	{
	  cerr << "Couldn't read socket" << endl;
	  return "Error";
	}
      i += nb;
    } while ((i < max) && (chaine[i-1] != '\n'));
  chaine[i-1] = '\0';
  return string(chaine);
}

int Socket::readMsg(void *buf, int toRead)
{
	int nb = recv(_sock, buf, toRead, 0);
	return nb;
}

int Socket::sendMsg(void *buf, int toSend)
{
	int nb = send(_sock, buf, toSend, 0);
	return nb;
}

int Socket::send4(unsigned long data)
{
    long dataSend = htonl(data);
    int nb = send(_sock, (char*)&dataSend, 4, 0);
    return nb;
}

int Socket::read4(long* data)
{
    char dataRecv[4];
    int nb = recv(_sock, dataRecv, 4, 0);
    unsigned long temp = 0;
    temp |= (dataRecv[0] & 0xFF) << 24;
    temp |= (dataRecv[1] & 0xFF) << 16;
    temp |= (dataRecv[2] & 0xFF) << 8;
    temp |= (dataRecv[3] & 0xFF) << 0;
    *data = temp;
	return nb;
}

int Socket::closeSock()
{
	int res = close(_sock);
	return res;
}
